<template>
    <div style="height: 100%">
        <vxe-grid
            ref="xTable"
            v-bind="gridOptions"
            :data="tableData"
            :columns="column"
            :header-cell-style="headerCellStyle || {}"
            :sort-config="{ defaultSort: { field: '', order: '' }, remote: true }"
            :filter-config="{ remote: true }"
            :checkbox-config="{ strict: true, reserve: true, checkRowKeys: checkRowKeys }"
            @sort-change="handleSort"
            @filter-change="handleFilter"
            @checkbox-change="checkboxChange"
            @checkbox-all="selectAllCheckboxChange"
            @cell-dblclick="handleDbclick"
            @cell-click="handleCellClick"
            auto-resize
            resizable
            stripe
            border
            size="mini"
            height="100%"
            show-header-overflow
            show-overflow
        >
            <!--筛选  -->
            <!-- v-if="item.filterType === 'search'" -->
            <template #filter="{ $panel, column }">
                <div>
                    <el-input
                        ref="searchInput"
                        class="my-input"
                        type="type"
                        v-for="(option, index) in column.filters"
                        :key="index"
                        v-model="option.data"
                        @input="$panel.changeOption($event, !!option.data, option)"
                    />
                </div>
            </template>
            <!--自定义插槽-->
            <template #default="{ column, row }">
                <!-- render渲染 优先级最高 -->
                <span
                    v-if="column.contentRender && typeof column.contentRender === 'function'"
                    :style="getCellStyle(column, row[column.property], row)"
                >
                    {{ column.contentRender(row[column.property], row) || '--' }}
                </span>
                <!-- 插槽渲染 slotName用于大部分字段用于同一种插槽展示内容时 -->
                <slot
                    v-else-if="$scopedSlots[column.slotName || column.property]"
                    :name="column.slotName || column.property"
                    v-bind="{ column, row }"
                ></slot>
                <span v-else>
                    {{ row[column.property] === 0 || (row[column.property] && (row[column.property] + '').trim()) ? row[column.property] : '--' }}
                </span>
                {{ show(column) }}
            </template>
            <template #operation="event">
                {{ show(event) }}
            </template>
        </vxe-grid>

        <div v-if="paging" class="block">
            <RiskPagination :paging="paging" @page-change="$emit('page-change')"></RiskPagination>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch, Emit } from 'vue-property-decorator';
import RiskPagination from '@/common/components/risk-pagination.vue';
import { VueObject, PageVO, TableConfigVO, ColumnVO } from '@/common/vo';

@Component({ name: 'RiskGridPlus', components: { RiskPagination } })
export default class RiskGridPlus extends Vue {
    @Prop() tableData: any[];
    @Prop() tableConfig: TableConfigVO;
    @Prop() column: ColumnVO[];
    @Prop() paging: PageVO;
    @Prop() sort: string;
    @Prop() searchParams: any;
    @Prop() headerCellStyle: any;

    selectionRows: any[] = [];
    checkRowKeys: any[] = []; // 已勾选数据
    selectedAll: boolean = false;
    cancelAll: boolean = false;

    /**
     * 监听表格数据发生变化时渲染勾选
     */
    @Watch('tableData', { deep: true })
    WatchTableData(newData: any, oldData: any) {
        if (this.selectedAll && !this.cancelAll) {
            newData.forEach(element => {
                if (this.checkRowKeys.includes(element[this.tableConfig.rowKey])) {
                    this.$nextTick(() => {
                        (this.$refs['xTable'] as VueObject).setCheckboxRow(element, true);
                    });
                }
            });
        }
        console.log('已勾选项:', this.checkRowKeys);
    }
    show(event) {
        console.log(event, '----------');
        // console.log(event.column.contentRender);
        // let column = event.column;
        // return column.contentRender(event.row[column.property]);
    }

    /**
     * 监听列发生变化时渲染放大镜icon
     * @remark 暂时还不能修改固定列的icon 未排查原因 待完善
     */
    @Watch('column', { immediate: true, deep: true })
    WatchColumn(newData: any, oldData: any) {
        this.$nextTick(() => {
            let data = this.getTreeToArr(newData);
            console.log(data, 'data');
            // 需要改icon的列
            const magnifyingGlass = data.filter(i => i.filterType === 'search').map(i => i.field);
            // 所有列dom
            const cols = (this.$refs['xTable'] as VueObject).getColumns();
            // 找到需要改icon的列domids
            let magnifyingGlassDomIds = [];
            cols.forEach(element => {
                if (magnifyingGlass.includes(element.property)) {
                    magnifyingGlassDomIds.push(element.id);
                }
            });
            magnifyingGlassDomIds.forEach(colid => {
                (this.$refs['xTable'] as VueObject).$el.querySelector(`th[data-colid=${colid}] .vxe-icon--funnel`).className =
                    'vxe-filter--btn el-icon-search';
            });
        });
    }

    // 类似于树形结构转化为数组
    getTreeToArr(newData: any) {
        let data = [];
        newData.map(item => {
            if (item.children) {
                data = data.concat(this.getTreeToArr(item.children));
            } else {
                data.push(item);
            }
        });
        return data;
    }

    mounted() {
        // 清除 原生HTML title
        // this.$nextTick(() => {
        //     ((this.$refs['xTable'] as VueObject) as any).$el.querySelector('span[title="全选/取消"]').title = '';
        // });
    }

    /**
     * 选中/取消 所有页事件
     */
    handleDropdown(value: string): void {
        if (value === 'selectedAll') {
            this.selectedAll = true;
            this.cancelAll = false;
            this.$emit('getAllData');
        }
        if (value === 'cancelAll') {
            this.selectedAll = false;
            this.cancelAll = true;
            this.checkRowKeys = [];
            (this.$refs['xTable'] as VueObject).clearCheckboxRow();
            (this.$refs['xTable'] as VueObject).clearCheckboxReserve();
        }
        console.log('已勾选项:', this.checkRowKeys);
    }

    handleSelectAll() {
        this.checkRowKeys = this.tableConfig.allRowKeys;
        (this.$refs['xTable'] as VueObject).setAllCheckboxRow(true);
        console.log('已勾选项:', this.checkRowKeys);
    }

    /**
     * 表格复选框勾选事件
     */
    checkboxChange({ records, checked, row }): void {
        if (checked) {
            this.checkRowKeys.push(row[this.tableConfig.rowKey]);
        } else {
            this.checkRowKeys = this.checkRowKeys.filter(i => i !== row[this.tableConfig.rowKey]);
        }
        console.log('已勾选项:', this.checkRowKeys);
    }

    /**
     * 表格复选框勾选事件
     */
    selectAllCheckboxChange({ records, checked }): void {
        if (checked) {
            const checkedKeys = records.map(i => i[this.tableConfig.rowKey]);
            this.checkRowKeys = [...new Set(this.checkRowKeys.concat(checkedKeys))];
        } else {
            const checkedKeys = this.tableData.map(i => i[this.tableConfig.rowKey]);
            this.checkRowKeys = this.filterArr(this.checkRowKeys, checkedKeys);
        }
        console.log('已勾选项:', this.checkRowKeys);
    }

    /**
     * 表格排序事件
     */
    @Emit('page-change')
    handleSort({ property, order }): void {
        let sort = '';
        if (order) {
            const sortField = this.column.find(i => i.field === property)?.sortField || property;
            sort = (sortField + ' ' + order).toUpperCase();
        }
        this.paging && (this.paging.currentPage = 1);
        this.searchParams.sort = sort;
        // this.$emit('update:sort', sort);
    }

    /**
     * 表格搜索/筛选事件
     */
    @Emit('page-change')
    handleFilter({ field, values, datas }): void {
        const col = this.column.find(i => i.field === field);
        // 漏洞用values 放大镜用datas
        let searchParams = this.searchParams;
        // searchParams[field] = values.filter(Boolean).length ? values : datas.join('');
        searchParams[col.filterField ?? field] = col.filterType === 'search' ? datas.join('') : values;
        this.paging && (this.paging.currentPage = 1);
        this.$emit('update:searchParams', searchParams);
    }

    /**
     * 单元格双击事件
     */
    @Emit('cell-dblclick')
    handleDbclick({ row }): any {
        return row;
    }
    /**
     * 单元格点击
     */
    @Emit('cell-click')
    handleCellClick($event) {
        return $event;
    }

    isTemplateCell(row: any): boolean {
        // 插槽
        if (this.$scopedSlots[row.prop || row.val || row.field]) {
            return true;
        }
        // render
        if (row.render && typeof row.render === 'function') {
            return true;
        }
        return false;
    }

    getCellStyle(col: any, value: any, record: any): any {
        if (col.style && typeof col.style === 'function') {
            return col.style(value, record);
        } else if (col.style && typeof col.style === 'object') {
            return col.style;
        } else {
            return null;
        }
    }

    /**
     * 两个对象数组, 筛选出数组一不包含数组二的元素
     */
    filterArr(arr1: string[], arr2: string[]): string[] {
        let uid1 = [];
        let uid2 = [];
        for (let i in arr1) {
            uid1.push(arr1[i]);
        }
        for (let i in arr2) {
            uid2.push(arr2[i]);
        }
        const arr = [...uid1, ...uid2];
        const newArr = arr.filter(item => {
            return !(uid1.includes(item) && uid2.includes(item));
        });
        return newArr;
    }

    /**
     * 清空已勾选数据
     */
    resetCheckRowKeys() {
        this.handleDropdown('cancelAll');
    }

    /**
     * 合并表格单元格
     */
    mergeRowMethod($event) {
        console.log($event.column.property, 'event++++++++++');
    }

    handle($event) {
        if ($event.column.property == 'fundCode') {
            console.log($event, '++++++++++++++++++++++=');
            return;
        }
        console.log($event, 'evv');
    }
}
</script>

<style lang="scss" scoped>
.my-input {
    margin: 10px;
    width: 150px;
}

/deep/ .vxe-table .el-button + .el-button {
    margin-left: 0;
}

/deep/ .vxe-table .vxe-table--header {
    width: 10px !important;
}
.class1 {
    color: red;
}
</style>
